package com.fl.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTML;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.fl.config.AlipayConfigInfo.*;

@Controller
public class AlipayController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static void returnResponse (HttpServletResponse response,String form){
        try {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //创建订单整合Rabbitmq实现订单超时关闭交易
    @GetMapping("/createGrade")
    public void createGrade(HttpServletResponse response)  {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(new Date());
            Message message = new Message(("关闭交易当前时间："+format).getBytes(StandardCharsets.UTF_8));
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            String outTradeNo = "33"; // 商户订单号，商户网站订单系统中唯一订单号，必填
            String totalAmount = "99.9"; // 付款金额，必填
            String subject = "羽绒服"; // 订单名称，必填
            String body = "冬日神器"; // 商品描述，可空
            String buyer_id = "ggbwwk8873@sandbox.com";
            request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                    + "\"total_amount\":\"" + totalAmount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"buyer_id\":\"" + buyer_id + "\","
                    +"      \"goods_detail\":[{" +
                    "        \"goods_id\":\"123214421311\"," +
                    "\"goods_name\":\"ipad\"," +
                    "\"quantity\":1," +
                    "\"price\":2000," +
                    "\"goods_category\":\"34543238\"," +
                    "\"categories_tree\":\"124868003|126232002|126252004\"," +
                    "\"body\":\"特价手机\"," +
                    "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
                    "        }],"
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            // 在公共参数中设置回跳和通知地址
            //用户支付成功返回地址
            request.setReturnUrl(return_url);
            //商家接收地址
            request.setNotifyUrl(notify_url);
            AlipayTradePagePayResponse payResponse = alipayClient.pageExecute(request);
            rabbitTemplate.convertAndSend("direct.delay.exchange","DelayKey",message);
            String form = payResponse.getBody();
            returnResponse(response,form);
        } catch (AlipayApiException  e) {
            e.printStackTrace();
        }
    }

    //查询订单信息
    @GetMapping("/query")
    public void queryTrace(HttpServletResponse response) throws Exception {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"33\"," +
                "      \"query_options\":[" +
                "        \"trade_settle_info\"" +
                "      ]" +
                "  }");
        AlipayTradeQueryResponse tradeQueryResponse = alipayClient.execute(request);
        String body = tradeQueryResponse.getBody();
        returnResponse(response,body);
    }

    //撤销订单
    @GetMapping("/cancelTrade")
    public void cancelTrade(HttpServletResponse response) throws Exception{
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"33\"," +
                "\"trade_no\":\"\"" +
                "}");
        AlipayTradeCancelResponse tradeCancelResponse = alipayClient.execute(request);
        String body = tradeCancelResponse.getBody();
        returnResponse(response,body);
        if (tradeCancelResponse.isSuccess()){
            System.out.println("删除订单或者修改订单状态");
        }
    }

    //交易退款
    @GetMapping("/refundTrade")
    public void refundTrade(HttpServletResponse response) throws Exception{
        while (true){
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            String refund_amount = "50";
            request.setBizContent("{" +
                    "\"out_trade_no\":\"33\"," +
                    "\"trade_no\":\"\"," +
                    "\"refund_amount\":50," +
                    "\"refund_reason\":\"正常退款\"," +
                    "\"out_request_no\":\"HZ01RF001\"," +
                    "      \"refund_royalty_parameters\":[{" +
                    "        \"royalty_type\":\"transfer\"," +
                    "\"trans_out\":\"mswwrs2745@sandbox.com\"," +
                    "\"trans_out_type\":\"loginName\"," +
                    "\"trans_in_type\":\"loginName\"," +
                    "\"trans_in\":\"ggbwwk8873@sandbox.com\"," +
                    "\"amount\":0.1," +
                    "\"desc\":\"分账给ggbwwk8873@sandbox.com\"" +
                    "        }]" +
                    "  }");
            AlipayTradeRefundResponse alipayTradeRefundResponse = alipayClient.execute(request);
            String form = alipayTradeRefundResponse.getBody();
            returnResponse(response,form);
            if (alipayTradeRefundResponse.isSuccess()){
                System.out.println("退款金额："+refund_amount);
                break;
            }
            Thread.sleep(5000);
        }
    }


    //查询订单下载地址
    @GetMapping("/orderQuery")
    public void orderQuery(HttpServletResponse response) throws AlipayApiException {
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        request.setBizContent("{" +
                "\"bill_type\":\"trade\"," +
                "\"bill_date\":\"2021-08-25\"" +
                "  }");
        AlipayDataDataserviceBillDownloadurlQueryResponse queryResponse = alipayClient.execute(request);
        String form = queryResponse.getBody();
        System.out.println(form);
        returnResponse(response,form);
        if (queryResponse.isSuccess()){
            System.out.println("查询成功");
        }
    }

}
